package com.jyxd.web.controller.dictionary;

import com.jyxd.web.data.dictionary.RespiratorDictonary;
import com.jyxd.web.data.dto.HttpResult;
import com.jyxd.web.data.user.User;
import com.jyxd.web.service.assessment.basic.IBedBindDeviceService;
import com.jyxd.web.service.dictionary.RespiratorDictonaryService;
import com.jyxd.web.util.HttpCode;
import com.jyxd.web.util.JsonArrayValueProcessor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.*;

import static com.jyxd.web.util.ExecuteUtil.errorIfEmpty;
import static com.jyxd.web.util.ExecuteUtil.isEmpty;
import static com.jyxd.web.util.UUIDUtil.getUUID;

/**
 * 呼吸机字典
 */
@Api(tags = "呼吸机字典相关接口")
@Controller
@RequestMapping(value = "/respiratorDictonary")
public class RespiratorDictonaryController {

    private static Logger logger = LoggerFactory.getLogger(RespiratorDictonaryService.class);

    @Autowired
    private RespiratorDictonaryService respiratorDictonaryService;
    @Autowired
    private IBedBindDeviceService bedBindDeviceService;

    /**
     * 增加一条呼吸机字典
     *
     * @return
     */
    @ApiOperation("增加一条呼吸机字典记录")
    @RequestMapping(value = "/insert", method = {RequestMethod.POST})
    @ResponseBody
    public String insert(@RequestBody RespiratorDictonary respiratorDictonary,HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "系统开小差了，请稍后再试");
        json.put("code", HttpCode.EXISTING_CODE.getCode());

        User user=(User)session.getAttribute("user");
        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            if(StringUtils.isNotEmpty(tenantId)){
                respiratorDictonary.setTenantId(tenantId);
            }
        }
        respiratorDictonary.setId(getUUID());
        respiratorDictonary.setCreateDate(new Date());
        respiratorDictonaryService.insert(respiratorDictonary);
        json.put("code", HttpCode.OK_CODE.getCode());
        json.put("msg", "添加成功");
        return json.toString();
    }

    /**
     * 更新呼吸机字典
     *
     * @param
     * @return
     */
    @ApiOperation("更新呼吸机字典")
    @RequestMapping(value = "/update", method = {RequestMethod.POST})
    @ResponseBody
    public HttpResult update(@RequestBody(required = false) RespiratorDictonary respiratorDictonary,HttpSession session) {
        try {
            errorIfEmpty(respiratorDictonary, "参数数据不能为空");
            User user=(User)session.getAttribute("user");
            if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
                String tenantId = user.getTenantId();
                if(StringUtils.isNotEmpty(tenantId)){
                    respiratorDictonary.setTenantId(tenantId);
                }
            }
            respiratorDictonary.setCreateDate(new Date());
            if (isEmpty(respiratorDictonary.getId())) {
                respiratorDictonary.setId(getUUID());
                respiratorDictonaryService.insert(respiratorDictonary);
            } else
                respiratorDictonaryService.update(respiratorDictonary);
            return new HttpResult(200, "数据更新成功");
        } catch (Exception e) {
            return new HttpResult(500, e.getMessage());
        }
    }

    /**
     * 删除呼吸机字典
     *
     * @param map
     * @return
     */
    @ApiOperation("删除呼吸机字典记录")
    @RequestMapping(value = "/delete", method = {RequestMethod.POST})
    @ResponseBody
    public String delete(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "系统开小差了，请稍后再试。");
        if (map.containsKey("id")) {
            int i = respiratorDictonaryService.deleteById(map.get("id").toString());
            if (i==1) {
                json.put("msg", "删除成功");
            } else {
                json.put("msg", "删除失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据主键id查询呼吸机字典
     *
     * @param map
     * @return
     */
    @ApiOperation("根据主键id查询呼吸机字典记录")
    @RequestMapping(value = "/queryData", method = RequestMethod.POST)
    @ResponseBody
    public String queryData(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        if (map != null && map.containsKey("id")) {
            RespiratorDictonary respiratorDictonary = respiratorDictonaryService.queryData(map.get("id").toString());
            if (respiratorDictonary != null) {
                json.put("msg", "查询成功");
                json.put("data", JSONObject.fromObject(respiratorDictonary));
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据条件分页查询呼吸机字典记录列表（也可以不分页）
     *
     * @param map
     * @return
     */
    @ApiOperation("根据条件分页查询呼吸机字典记录列表（也可以不分页）")
    @RequestMapping(value = "/queryList", method = RequestMethod.POST)
    @ResponseBody
    public String queryList(@RequestBody(required = false) Map<String, Object> map,HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        if (map == null) map = new HashMap<>();
        User user=(User)session.getAttribute("user");
        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            if(StringUtils.isNotEmpty(tenantId)){
                map.put("tenantId",tenantId);
            }
        }
        if (map.containsKey("start")) {
            int totalCount = respiratorDictonaryService.queryNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            json.put("totalCount", totalCount);
        }
        List<RespiratorDictonary> list = respiratorDictonaryService.queryList(map);
        if (list != null && list.size() > 0) {
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Date.class, new JsonArrayValueProcessor());
            json.put("data", JSONArray.fromObject(list,jsonConfig));
            json.put("msg", "查询成功");
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 床位绑定呼吸机
     *
     * @param map
     * @return
     */
    @ApiOperation("呼吸机绑定盒子")
    @RequestMapping(value = "/bindRespirator", method = RequestMethod.POST)
    @ResponseBody
    public String bindRespirator(@RequestBody(required = false) Map<String, Object> map,HttpSession session) {
        User user=(User)session.getAttribute("user");
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        String bedCode = (String) map.get("bedCode");
        String respiratorNumbers = (String) map.get("respiratorNumbers");
        //清空绑定床位的呼吸机
        respiratorDictonaryService.cleanByBedCode(bedCode);
        //更新呼吸机数据数据
        respiratorDictonaryService.updateByRespitatorNumbers(bedCode, respiratorNumbers);

        String dateTime = "";
        if(map.containsKey("dateTime")){
            dateTime = map.get("dateTime").toString();
        }
        bedBindDeviceService.bind(user,bedCode,respiratorNumbers,dateTime,0);
        json.put("data", null);
        json.put("msg", "绑定成功");
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 查询绑定盒子的呼吸机
     *
     * @param map
     * @return
     */
    @ApiOperation("查询绑定盒子的呼吸机")
    @RequestMapping(value = "/bindBoxList", method = RequestMethod.POST)
    @ResponseBody
    public String bindBoxList(@RequestBody(required = false) Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        if (map == null) map = new HashMap<>();
        User user=(User)session.getAttribute("user");
        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            if(StringUtils.isNotEmpty(tenantId)){
                map.put("tenantId",tenantId);
            }
        }
        List<Map<String, Object>> list = respiratorDictonaryService.queryBindBoxList();
        json.put("data", list);
        json.put("msg", "绑定成功");
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }
}
